package com.california.payopenapi.utils;
 
import java.io.UnsupportedEncodingException;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
import org.apache.commons.codec.digest.DigestUtils;

/**
 * @Description: MD5 签名工具类
 * @author: KeyboardMan
 * @Date: Create in 2018-12-05:21:27
 */
public class MD5Sign {

    /**
     * 方法描述:将字符串MD5加码 生成32位md5码
     * @param inStr
     * @return
     */
    public static String md5(String inStr) {
        try {
            return DigestUtils.md5Hex(inStr.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("MD5签名过程中出现错误");
        }
    }

    /**
     * 方法描述:签名字符串
     * @param params 需要签名的参数
     * @param appSecret 签名密钥
     * @return
     */
    public static String sign(Map<String, Object> params, String appSecret) {
        StringBuilder valueSb = new StringBuilder();
        params.put("secretKey", appSecret);
        // 将参数以参数名的字典升序排序
        Map<String, Object> sortParams = new TreeMap<>(params);
        Set<Entry<String, Object>> entrys = sortParams.entrySet();
        // 遍历排序的字典,并拼接value1+value2......格式
        for (Entry<String, Object> entry : entrys) {

            valueSb.append(entry.getValue());
        }
        params.remove("secretKey");
        return md5(valueSb.toString());
    }

    /**
     * 方法描述:验证签名
     * @param secretKey 加密秘钥
     * @param params 参数
     * @return
     * @throws Exception
     */
    public static boolean verify(Map<String, Object> params, String secretKey) throws Exception {
        String sign = params.get("sign").toString();
        // 移除原有sign
        params.remove("sign");
        params.put("secretKey", secretKey);
        // 将参数以参数名的字典升序排序
        Map<String, Object> sortParams = new TreeMap<>(params);
        Set<Entry<String, Object>> entrys = sortParams.entrySet();
        // 遍历排序的字典,并拼接value1+value2......格式
        StringBuilder valueSb = new StringBuilder();
        for (Entry<String, Object> entry : entrys) {
            valueSb.append(entry.getValue());
        }
        String mysign = md5(valueSb.toString());
        if (mysign.equals(sign)) {
            return true;
        } else {
            return false;
        }
    }
}
